import random

import os
from django.db.models import Max, Min
from django.shortcuts import render

# Create your views here.
from rest_framework import generics, filters, mixins

from admin.return_tools import SuccessHR, ErrorHR
from admin.serializers import *
from databases.serializers import *
from rest_api.mixins.EmptyPageListViewMixin import PageListView
from rest_api.serializers import *
from rest_api.utils.common_util import needReplaceAPK, handle_uploaded_file, checkVersionMoveAPK, recoverAPK, \
    uploaded_hardware_file
from rest_api.utils.lucky_sport_pagination import LuckyScportPagination
from rest_api.utils.memcache_utils import create_memcache
from rest_api.utils.page_util import page_info
from rest_api.utils.upload import *


class AdminLogin(generics.CreateAPIView):
    """
    后台账户登录
    """
    queryset = AdminUser.objects.all()
    serializer_class = PostAdminLoginSerializer
    permission_validate = False

    def create(self, request, *args, **kwargs):
        data = request.data
        _phone = data.get('phone')
        _password = data.get('password')
        return_dict = {}
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            try:
                _admin = AdminUser.objects.get(account=_phone)
                if _admin.password == _password:
                    _serializer = AdminUserSerializer(_admin)

                    request.session['web_user'] = AdminUserSerializer(_admin).data
                    return Response(_serializer.data, status=status.HTTP_200_OK)
                else:
                    return_dict['detail'] = {"message": "密码错误请重新输入"}
                    return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
            except:
                return_dict['detail'] = {"message": "该账户无权限登录"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class AdminChangePassword(generics.CreateAPIView):
    """
    修改密码
    """
    queryset = AdminUser.objects.all()
    serializer_class = PostAdminChangePasswordSerializer
    permission_validate = False

    def create(self, request, *args, **kwargs):
        data = request.data
        _password = data.get('password')
        _old = data.get('old')
        return_dict = {}
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            try:
                _admin = AdminUser.objects.get(pk=kwargs.get('PK'))
                if _admin.password == _old:
                    _admin.password = _password
                    _admin.save()
                    return_dict['result'] = {"message": "修改成功"}
                    return Response(return_dict, status=status.HTTP_200_OK)
                else:
                    return_dict['detail'] = {"message": "老密码错误"}
                    return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
            except:
                return_dict['detail'] = {"message": "该账户无权限修改密码"}
                return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class AdminForgetPassword(generics.CreateAPIView):
    """
    忘记密码
    """
    queryset = AdminUser.objects.all()
    serializer_class = PostAdminForgetPasswordSerializer
    permission_validate = False

    def create(self, request, *args, **kwargs):
        data = request.data
        return_dict = {}
        try:
            _admin = AdminUser.objects.get(account=kwargs.get('account'))
            _code = data.get('code')
            _password = data.get('password')
            _client = create_memcache()
            _message = eval(_client.get('message_' + _admin.account))
            serializer = self.get_serializer(data=request.data)
            if serializer.is_valid(raise_exception=True):
                if _code == str(_message):
                    _admin.password = _password
                    _admin.save()
                    return_dict['result'] = {"message": "密码修改成功"}
                    return Response(return_dict, status=status.HTTP_200_OK)
                else:
                    return_dict['detail'] = {"message": "验证码错误"}
                    return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)
        except:
            return_dict['detail'] = {"message": "该账户无权限修改密码"}
            return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class UploadInformation(generics.CreateAPIView):
    """
    新增资讯
    """
    queryset = Information.objects.all()
    serializer_class = PostSaveInfoSerializer
    permission_validate = False

    def create(self, request, *args, **kwargs):
        data = request.data
        _cover = data.get('cover')
        _background = data.get('background')
        _text = data.get('text')
        _title = data.get('title')
        _type = data.get('type')
        _url = data.get('url')
        _id = request.query_params.get('PK')
        # serializer = self.get_serializer(data=request.data)
        # return_dict = {}
        # try:
        # if serializer.is_valid(raise_exception=True):
        if _id:
            _info = Information.objects.get(pk=_id)
            _info.info_text = _text
            _info.cover_image = _cover
            _info.background_image = _background
            _info.info_title = _title
            _info.type = _type
            _info.url = _url
            _info.save()
            _serializer = InformationSerializer(_info)
            return Response(_serializer.data, status=status.HTTP_201_CREATED)
        else:
            # 查找最大排序号码
            _max_order = Information.objects.aggregate(Max('order')).get('order__max', 0)
            _info = Information()
            _info.info_text = _text
            _info.cover_image = _cover
            _info.background_image = _background
            _info.info_title = _title
            _info.type = _type
            _info.url = _url
            _info.order = _max_order + 1
            _info.save()
            _serializer = InformationSerializer(_info)
            return Response(_serializer.data, status=status.HTTP_201_CREATED)
        # except Exception as e:
        #     return_dict['detail'] = {"message": "资讯详情中某项参数为空，无法保存"}
        #     return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class UpInfomation(generics.CreateAPIView):
    """
    排序上升
    """

    def post(self, request, *args, **kwargs):
        # 如果已经是最小,不能排序
        # 否则和上一个信息调换order
        _min_order = Information.objects.filter(is_delete=False).aggregate(Min('order')).get('order__min', 0)
        _infomation = Information.objects.get(pk=kwargs['PK'])
        result_dict = {}
        result_dict['code'] = 400
        if _infomation.order == _min_order:
            result_dict['message'] = '已经是排序第一'
            return Response(result_dict, status=status.HTTP_200_OK)
        else:
            _pre_info = Information.objects.filter(is_delete=False, order__lt=_infomation.order).order_by(
                'order').last()
            _t = _infomation.order
            _infomation.order = _pre_info.order
            _pre_info.order = _t
            _pre_info.save()
            _infomation.save()
            result_dict['code'] = 200
            result_dict['message'] = '修改成功'
            return Response(result_dict, status=status.HTTP_200_OK)


class DownInfomation(generics.CreateAPIView):
    """
    排序下降
    """

    def post(self, request, *args, **kwargs):
        # 如果已经是最小,不能排序
        # 否则和上一个信息调换order
        _max_order = Information.objects.filter(is_delete=False).aggregate(Max('order')).get('order__max', 0)
        _infomation = Information.objects.get(pk=kwargs['PK'])
        result_dict = {}
        result_dict['code'] = 400
        if _infomation.order == _max_order:
            result_dict['message'] = '已经是排序末尾'
            return Response(result_dict, status=status.HTTP_200_OK)
        else:
            _pre_info = Information.objects.filter(is_delete=False, order__gt=_infomation.order).order_by(
                'order').first()
            _t = _infomation.order
            _infomation.order = _pre_info.order
            _pre_info.order = _t
            _pre_info.save()
            _infomation.save()
            result_dict['code'] = 200
            result_dict['msg'] = '修改成功'
            return Response(result_dict, status=status.HTTP_200_OK)


class TopInfomation(generics.CreateAPIView):
    """
    资讯 置顶操作
    """

    def post(self, request, *args, **kwargs):
        # 如果已经是最小,不能排序
        # 否则和上一个信息调换order
        _infomation = Information.objects.get(pk=kwargs['PK'])
        result_dict = {}
        _infomation.is_top = True
        _infomation.save()
        result_dict['code'] = 200
        result_dict['msg'] = '置顶成功'
        return Response(result_dict, status=status.HTTP_200_OK)


class CancelTopInfomation(generics.CreateAPIView):
    """
    资讯 置顶操作
    """

    def post(self, request, *args, **kwargs):
        # 如果已经是最小,不能排序
        # 否则和上一个信息调换order
        _infomation = Information.objects.get(pk=kwargs['PK'])
        result_dict = {}
        _infomation.is_top = False
        _infomation.save()
        result_dict['code'] = 200
        result_dict['msg'] = '取消置顶成功'
        return Response(result_dict, status=status.HTTP_200_OK)


class GetInfoPage(generics.ListAPIView):
    """
     _pageSize = request.query_params.get('pageSize')
        _pageNum = request.query_params.get('pageNo')
        获取所有资讯分页
    """
    queryset = Information.objects.filter(is_delete=False).order_by('order')
    serializer_class = InformationSerializer
    pagination_class = LuckyScportPagination


class GetInfoDetail(generics.ListAPIView):
    """
    资讯详情
    """
    queryset = Information.objects.all()
    serializer_class = InformationSerializer
    permission_validate = False

    def get(self, request, *args, **kwargs):
        _info = Information.objects.get(pk=kwargs.get('PK'))
        _serializers = InformationSerializer(_info)
        return Response(_serializers.data, status=status.HTTP_200_OK)


class DeleteInfoDetail(generics.CreateAPIView):
    """
    删除资讯
    """
    queryset = Information.objects.all()
    serializer_class = InformationSerializer
    permission_validate = False

    def post(self, request, *args, **kwargs):
        return_dict = {}
        _info = Information.objects.get(pk=kwargs.get('PK'))
        _info.is_delete = True
        _info.save()
        return_dict['result'] = {"message": "删除成功"}
        return Response(return_dict, status=status.HTTP_200_OK)


class GetAffairsDetail(generics.ListAPIView):
    """
    帖子详情
    """
    queryset = AffairsRecord.objects.all()
    serializer_class = AffairsRecordSerializer
    permission_validate = False

    def get(self, request, *args, **kwargs):
        _info = AffairsRecord.objects.get(pk=kwargs.get('PK'))
        _serializers = AffairsRecordSerializer(_info)
        return Response(_serializers.data, status=status.HTTP_200_OK)


class IncreaseThumbsNumber(generics.CreateAPIView):
    queryset = AffairsRecord.objects.all()
    serializer_class = AdminAffairsRecordSerializer
    permission_validate = False

    def post(self, request, *args, **kwargs):
        _id = kwargs.get('PK')
        _base = request.query_params.get('base')
        return_dict = {}
        try:
            _affair = AffairsRecord.objects.get(pk=_id)
            _affair.base_thumbs_num = _affair.base_thumbs_num + int(_base)
            _affair.save()
            return Response({"message": "成功"}, status=status.HTTP_200_OK)
        except:
            return Response({"message": "失败"}, status=status.HTTP_400_BAD_REQUEST)


class PostAffairsDetail(generics.CreateAPIView):
    """
    帖子变更推荐状态
    """
    queryset = AffairsRecord.objects.all()
    serializer_class = AffairsRecordSerializer
    permission_validate = False

    def post(self, request, *args, **kwargs):
        _info = AffairsRecord.objects.get(pk=kwargs.get('PK'))
        if _info.is_recommend:
            _info.is_recommend = False
        else:
            _info.is_recommend = True
        _info.save()
        _serializers = AffairsRecordSerializer(_info)
        return Response(_serializers.data, status=status.HTTP_200_OK)


class GetAffairsRecordPage(generics.ListAPIView):
    """
    获取帖子分页
    """
    queryset = AffairsRecord.objects.all()
    serializer_class = AdminAffairsRecordSerializer
    permission_validate = False

    def list(self, request, *args, **kwargs):
        _info_list = AffairsRecord.objects.filter(is_delete=False).order_by('user_id').order_by('-create_time')
        _pageSize = request.query_params.get('pageSize')
        _pageNum = request.query_params.get('pageNo')
        _list = page_info(AdminAffairsRecordSerializer(_info_list, many=True).data, _pageSize, _pageNum)
        return Response(_list, status=status.HTTP_200_OK)


class DeleteAffairDetail(generics.CreateAPIView):
    """
    删除帖子
    """
    queryset = AffairsRecord.objects.all()
    serializer_class = AffairsRecordSerializer
    permission_validate = False

    def post(self, request, *args, **kwargs):
        return_dict = {}
        _info = AffairsRecord.objects.get(pk=kwargs.get('PK'))
        _info.is_delete = True
        _info.save()
        return_dict['result'] = {"message": "删除成功"}
        return Response(return_dict, status=status.HTTP_200_OK)


class GetTrainPage(generics.ListAPIView):
    """
    获取训练列表
    """
    queryset = Training.objects.filter(is_delete=False).order_by('order')
    serializer_class = TrainingSerializer
    permission_validate = False
    pagination_class = LuckyScportPagination


class UpTrain(generics.CreateAPIView):
    """
    排序上升 训练视频
    """

    def post(self, request, *args, **kwargs):
        # 如果已经是最小,不能排序
        # 否则和上一个信息调换order
        _min_order = Training.objects.filter(is_delete=False).aggregate(Min('order')).get('order__min', 0)
        _train = Training.objects.get(pk=kwargs['PK'])
        result_dict = {}
        result_dict['code'] = 400
        if _train.order == _min_order:
            result_dict['message'] = '已经是排序第一'
            return Response(result_dict, status=status.HTTP_200_OK)
        else:
            _pre_info = Training.objects.filter(is_delete=False, order__lt=_train.order).order_by(
                'order').last()
            _t = _train.order
            _train.order = _pre_info.order
            _pre_info.order = _t
            _pre_info.save()
            _train.save()
            result_dict['code'] = 200
            result_dict['message'] = '修改成功'
            return Response(result_dict, status=status.HTTP_200_OK)


class DownTrain(generics.CreateAPIView):
    """
    排序下降 训练视频
    """

    def post(self, request, *args, **kwargs):
        # 如果已经是最小,不能排序
        # 否则和上一个信息调换order
        _max_order = Training.objects.filter(is_delete=False).aggregate(Max('order')).get('order__max', 0)
        _train = Training.objects.get(pk=kwargs['PK'])
        result_dict = {}
        result_dict['code'] = 400
        if _train.order == _max_order:
            result_dict['message'] = '已经是排序末尾'
            return Response(result_dict, status=status.HTTP_200_OK)
        else:
            _pre_info = Training.objects.filter(is_delete=False, order__gt=_train.order).order_by(
                'order').first()
            _t = _train.order
            _train.order = _pre_info.order
            _pre_info.order = _t
            _pre_info.save()
            _train.save()
            result_dict['code'] = 200
            result_dict['message'] = '修改成功'
            return Response(result_dict, status=status.HTTP_200_OK)


class TopTrain(generics.CreateAPIView):
    """
    训练视频 置顶操作
    """

    def post(self, request, *args, **kwargs):
        # 如果已经是最小,不能排序
        # 否则和上一个信息调换order
        _train = Training.objects.get(pk=kwargs['PK'])
        result_dict = {}
        _train.is_top = True
        _train.save()
        result_dict['code'] = 200
        result_dict['message'] = '置顶成功'
        return Response(result_dict, status=status.HTTP_200_OK)


class CancelTopTrain(generics.CreateAPIView):
    """
    训练视频 取消置顶操作
    """

    def post(self, request, *args, **kwargs):
        # 如果已经是最小,不能排序
        # 否则和上一个信息调换order
        _train = Training.objects.get(pk=kwargs['PK'])
        result_dict = {}
        _train.is_top = False
        _train.save()
        result_dict['code'] = 200
        result_dict['message'] = '取消置顶成功'
        return Response(result_dict, status=status.HTTP_200_OK)


class GetTrainDetailAdmin(generics.ListAPIView):
    """
    获取训练详情
    """
    queryset = Training.objects.all()
    serializer_class = TrainingSerializer
    permission_validate = False

    def get(self, request, *args, **kwargs):
        _info_list = Training.objects.get(pk=kwargs.get('PK'))
        _serializers = TrainingSerializer(_info_list)
        return Response(_serializers.data, status=status.HTTP_200_OK)


class PostTrainDetail(generics.CreateAPIView):
    """
    帖子变更推荐状态
    """
    queryset = Training.objects.all()
    serializer_class = TrainingSerializer
    permission_validate = False

    def post(self, request, *args, **kwargs):
        try:
            _info = Training.objects.get(pk=kwargs.get('PK'))
            if _info.is_recommend:
                _info.is_recommend = False
            else:
                _info.is_recommend = True
            _info.save()
            _serializers = TrainingSerializer(_info)
            return Response(_serializers.data, status=status.HTTP_200_OK)
        except Exception as e:
            return Response(e.__repr__(), status=status.HTTP_400_BAD_REQUEST)


class DeleteTrain(generics.CreateAPIView):
    """
    删除训练
    """
    queryset = Training.objects.all()
    serializer_class = TrainingSerializer
    permission_validate = False

    def post(self, request, *args, **kwargs):
        return_dict = {}
        _info = Training.objects.get(pk=kwargs.get('PK'))
        _info.is_delete = True
        _info.save()
        return_dict['result'] = {"message": "删除成功"}
        return Response(return_dict, status=status.HTTP_200_OK)


class JudgeWarmTrain(generics.ListAPIView):
    """
    判断当前是否已存在热身视频
    request.query_params.get('id')
    """
    queryset = Training.objects.all()
    serializer_class = TrainingSerializer
    permission_validate = False

    def get(self, request, *args, **kwargs):
        return_dict = {}
        _id = request.query_params.get('id')
        if _id is '':
            try:
                _warm_train = Training.objects.get(is_warm_up=True, is_delete=False)
                return_dict = {"message": True}
                return Response(return_dict, status=status.HTTP_200_OK)
            except:
                return_dict = {"message": False}
                return Response(return_dict, status=status.HTTP_200_OK)
        else:
            try:
                _warm_train = Training.objects.get(is_warm_up=True, is_delete=False)
                if _warm_train.id == _id:
                    return_dict = {"message": True}
                    return Response(return_dict, status=status.HTTP_200_OK)
                else:
                    return_dict = {"message": False}
                    return Response(return_dict, status=status.HTTP_200_OK)
            except:
                return_dict = {"message": False}
                return Response(return_dict, status=status.HTTP_200_OK)


class PostSaveTraining(generics.CreateAPIView):
    """
    新增训练
    """
    queryset = Training.objects.all()
    serializer_class = PostSaveTrainSerializer
    permission_validate = False

    def create(self, request, *args, **kwargs):
        data = request.data
        _name = data.get('name')
        _background = data.get('background')
        _introduce = data.get('introduce')
        _video = data.get('video')
        _cover = data.get('cover')
        _is_warm = data.get('is_warm')
        _base = data.get('base')

        _id = request.query_params.get('PK')
        serializer = self.get_serializer(data=request.data)
        return_dict = {}
        try:
            if serializer.is_valid(raise_exception=True):
                try:
                    _warm_train = Training.objects.get(is_warm_up=True, is_delete=False)
                    if _is_warm:
                        _warm_train.is_warm_up = False
                        _warm_train.save()
                    if _id is not '':
                        _info = Training.objects.get(pk=_id)
                        _info.name = _name
                        _info.introduce = _introduce
                        _info.background_image = _background
                        _info.train_video = _video
                        _info.cover_image = _cover
                        _info.base_browse_num = _base
                        _info.is_warm_up = _is_warm
                        _info.save()
                        _serializer = TrainingSerializer(_info)
                        return Response(_serializer.data, status=status.HTTP_201_CREATED)
                    else:
                        _info = Training()
                        _info.name = _name
                        _info.introduce = _introduce
                        _info.is_warm_up = _is_warm
                        _info.background_image = _background
                        _info.train_video = _video
                        _info.base_browse_num = _base
                        _info.cover_image = _cover
                        _info.save()
                        _serializer = TrainingSerializer(_info)
                        return Response(_serializer.data, status=status.HTTP_201_CREATED)
                except:
                    if _id is not '':
                        _info = Training.objects.get(pk=_id)
                        _info.name = _name
                        _info.introduce = _introduce
                        _info.background_image = _background
                        _info.train_video = _video
                        _info.cover_image = _cover
                        _info.base_browse_num = _base
                        _info.is_warm_up = _is_warm
                        _info.save()
                        _serializer = TrainingSerializer(_info)
                        return Response(_serializer.data, status=status.HTTP_201_CREATED)
                    else:
                        _info = Training()
                        _info.name = _name
                        _info.introduce = _introduce
                        _info.is_warm_up = _is_warm
                        _info.background_image = _background
                        _info.train_video = _video
                        _info.base_browse_num = _base
                        _info.cover_image = _cover
                        _info.save()
                        _serializer = TrainingSerializer(_info)
                        return Response(_serializer.data, status=status.HTTP_201_CREATED)
        except Exception as e:
            return_dict['detail'] = {"message": "训练详情中某项参数为空，无法保存"}
            return Response(return_dict, status=status.HTTP_400_BAD_REQUEST)


class GetUserInfoList(generics.ListAPIView):
    """
    获取用户列表信息
    """
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer

    # permission_validate = False

    def list(self, request, *args, **kwargs):
        _info_list = UserInfo.objects.all().order_by('-create_time')
        _pageSize = request.query_params.get('pageSize')
        _pageNum = request.query_params.get('pageNo')
        _list = page_info(UserInfoSerializer(_info_list, many=True).data, _pageSize, _pageNum)
        return Response(_list, status=status.HTTP_200_OK)


class GetUserInfoListBySearch(generics.ListAPIView):
    """
    搜索用户列表
    request.query_params.get('search_text')
     request.query_params.get('pageSize')
request.query_params.get('pageNo')
    """
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer
    permission_validate = False

    def list(self, request, *args, **kwargs):
        _search = request.query_params.get('search_text')
        _info_list = UserInfo.objects.filter(
            Q(nick_name__icontains=_search) | Q(user__user_account__icontains=_search)).order_by('-create_time')

        _pageSize = request.query_params.get('pageSize')
        _pageNum = request.query_params.get('pageNo')
        _list = page_info(UserInfoSerializer(_info_list, many=True).data, _pageSize, _pageNum)
        return Response(_list, status=status.HTTP_200_OK)


class GetUserInfoDetailAdmin(generics.ListAPIView):
    """
    获取用户详情
    """
    queryset = UserInfo.objects.all()
    serializer_class = AdminUserInfoSerializer
    permission_validate = False

    def get(self, request, *args, **kwargs):
        _info_list = UserInfo.objects.get(pk=kwargs.get('PK'))
        _serializers = AdminUserInfoSerializer(_info_list)
        return Response(_serializers.data, status=status.HTTP_200_OK)


class GetUserBodyDataHistoryAdmin(generics.ListAPIView):
    """
    获取用户体脂称使用信息
    """
    queryset = BodyData.objects.all()
    serializer_class = AdminUserBodyDataHistorySerializer
    permission_validate = False

    def get(self, request, *args, **kwargs):
        _user_last = BodyData.objects.filter(user_id=kwargs.get('PK')).order_by('-start_time').first()
        _serializers = AdminUserBodyDataHistorySerializer(_user_last)
        return Response(_serializers.data, status=status.HTTP_200_OK)


class GetUploadToken(generics.ListAPIView):
    """
    获取上传凭证的接口
    """
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer
    permission_validate = False

    def get(self, request, *args, **kwargs):
        return_dict = {}
        return_dict['result'] = get_upload_token()
        return Response(return_dict, status=status.HTTP_200_OK)


class GetUploadVideoImage(generics.ListAPIView):
    """
    获取视频截图
    request.query_params.get('path')
    path 为视频地址
    """
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer
    permission_validate = False

    def get(self, request, *args, **kwargs):
        file_path = request.query_params.get('path')
        _path = get_video_image(file_path)
        return_dict = {}
        return_dict['result'] = {"path": _path}
        return Response(return_dict, status=status.HTTP_200_OK)


class UpdateUserVipAdmin(generics.UpdateAPIView):
    """
    PK userInfo:Id vip:True/False 更新用户vip信息
    """
    serializer_class = UserInfoSerializer
    permission_validate = False

    def put(self, request, *args, **kwargs):
        _userInfo = UserInfo.objects.get(pk=kwargs['PK'])
        _userInfo.is_vip = request.POST['vip']
        _userInfo.save()
        _serializer = self.get_serializer(_userInfo)
        return Response(_serializer.data, status=status.HTTP_200_OK)


class UpdateUserCertificationAdmin(generics.UpdateAPIView):
    """
    PK userInfo:Id isSertification:1/2 更新用户是否实名认证  0:未审核 1:已审核 2:审核失败 3:待审核
    """
    serializer_class = UserInfoSerializer
    permission_validate = False

    def put(self, request, *args, **kwargs):
        _userInfo = UserInfo.objects.get(pk=kwargs['PK'])
        _userInfo.is_certification = request.POST['isSertification']
        _userInfo.save()
        _serializer = self.get_serializer(_userInfo)
        return Response(_serializer.data, status=status.HTTP_200_OK)


class listUserCertification(generics.ListAPIView):
    """
    ?is_certification=3&pageSize=2&pageNo=1 根据审核结果获取用户列表
    """

    permission_validate = False

    def get(self, request, *args, **kwargs):
        if request.GET.get('is_certification', None):
            _info_list = UserInfo.objects.filter(is_certification=request.GET['is_certification'])
        else:
            _info_list = UserInfo.objects.filter(is_certification__gt=0)
        _pageSize = request.query_params.get('pageSize')
        _pageNum = request.query_params.get('pageNo')
        _list = page_info(UserInfoSerializer(_info_list, many=True).data, _pageSize, _pageNum)
        return Response(_list, status=status.HTTP_200_OK)


class SuggesionList(generics.ListAPIView):
    """
    用户意见列表
    """
    serializer_class = SuggestionRecordSerialiezer
    queryset = SuggestionRecordModel.objects.all()
    pagination_class = LuckyScportPagination

    permission_validate = False


class UpdateNickName(generics.CreateAPIView):
    """
    更改用户昵称 pk:user_info_id param[nick_name]
    """

    def post(self, request, *args, **kwargs):

        _nick_name = request.data.get('nick_name')
        result_dict = {}
        result_dict['code'] = 400
        try:
            ss = UserInfo.objects.get(Q(nick_name=_nick_name), ~Q(pk=kwargs['PK']))
            result_dict['message'] = '正在使用的昵称'
        except UserInfo.DoesNotExist:

            _user_info = UserInfo.objects.get(pk=kwargs['PK'])
            _user_info.nick_name = _nick_name
            _user_info.save()
            result_dict['message'] = '修改成功'
            result_dict['code'] = 200
        return Response(result_dict, status=status.HTTP_200_OK)


class DelName(generics.DestroyAPIView):
    """
    删除禁用昵称
    """

    def delete(self, request, *args, **kwargs):
        _id = kwargs['PK']
        banNameModel = BanNameModel.objects.get(pk=_id)
        banNameModel.is_delete = True
        banNameModel.save()
        return Response(BanNameSerializer(banNameModel).data, status=status.HTTP_200_OK)


class BanNameList(generics.ListAPIView):
    """
    获取禁用昵称列表
    """
    queryset = BanNameModel.objects.filter(is_delete=False)
    serializer_class = BanNameSerializer
    pagination_class = LuckyScportPagination


class PostBanName(generics.CreateAPIView):
    """
    修改新增 禁用名称 id name
    """

    def post(self, request, *args, **kwargs):
        _id = request.data['id']
        _name = request.data['name']
        if _id:
            banNameModel = BanNameModel.objects.get(pk=_id)
            banNameModel.name = _name
            banNameModel.save()
            return Response(BanNameSerializer(banNameModel).data, status=status.HTTP_200_OK)
        else:
            banNameModel = BanNameModel()
            banNameModel.name = _name
            banNameModel.save()
            return Response(BanNameSerializer(banNameModel).data, status=status.HTTP_201_CREATED)


class PostApkVersion(generics.CreateAPIView):
    """
    新增/修改 apk版本信息
    """
    permission_validate = False
    serializer_class = ApkVersionSerializer

    def post(self, request, *args, **kwargs):
        _id = request.data['id']
        # _id = None
        _apk_url = request.data.get('apk_url')
        _version_description = request.data['version_description']
        _version_no = request.data['version_no']
        # _version_description = '123'
        # _version_no = '0.1.0'
        if _id:
            _apk_version = ApkVersionModel.objects.get(pk=_id)
            _apk_version.version_description = _version_description
            _apk_version.save()

            if _apk_url:
                checkVersionMoveAPK(_version_no, _apk_url)
            return Response(ApkVersionSerializer(_apk_version).data, status=status.HTTP_200_OK)
        else:
            try:
                ApkVersionModel.objects.get(version_no=_version_no, is_delete=False)
                return Response({'code': 200, 'message': '已存在版本号'}, status=status.HTTP_200_OK)
            except ApkVersionModel.DoesNotExist:
                if not _apk_url:
                    return Response({'code': 200, 'message': '请上传文件'}, status=status.HTTP_200_OK)

                if checkVersionMoveAPK(_version_no, _apk_url):
                    _apk_version = ApkVersionModel()
                    _apk_version.version_no = _version_no
                    _apk_version.version_description = _version_description
                    _apk_version.save()
                return Response({'code': 200, 'message': '上传成功'}, status=status.HTTP_201_CREATED)


class UpLoadAPK(generics.CreateAPIView):
    """
    上传apk
    """
    serializer_class = ApkVersionSerializer

    permission_validate = False

    def post(self, request, *args, **kwargs):
        _file = request.FILES.get('apk', None)
        if _file:
            url = handle_uploaded_file(_file)
            return Response({'code': 200, 'message': url}, status=status.HTTP_200_OK)
        else:
            return Response({'code': 200, 'message': '请上传文件'}, status=status.HTTP_200_OK)


class UpLoadHandWareFile(generics.CreateAPIView):
    """
    上传固件升级包文件
    """

    permission_validate = False

    def post(self, request, *args, **kwargs):
        _file = request.FILES.get('hardware', None)
        if _file:
            url = uploaded_hardware_file(_file)
            return Response({'code': 200, 'message': url}, status=status.HTTP_200_OK)
        else:
            return Response({'code': 200, 'message': '请上传文件'}, status=status.HTTP_200_OK)


class PostHardwareVersion(generics.CreateAPIView):
    """
    新增/修改 固件版本信息 category manufacture hw_version hardware_url fw_version
    """
    permission_validate = False
    serializer_class = ApkVersionSerializer

    def post(self, request, *args, **kwargs):
        _category = request.data['category']
        _manufacture = request.data['manufacture']
        _hw_version = request.data['hw_version']
        _hardware_url = request.data['hardware_url']
        _fw_version = request.data['fw_version']

        try:
            HardwareVersionModel.objects.get(category=_category, manufacture=_manufacture, hw_version=_hw_version,
                                             fw_version=_fw_version, is_delete=False)
            return Response({'code': 200, 'message': '已存在版本号'}, status=status.HTTP_200_OK)
        except HardwareVersionModel.DoesNotExist:
            if not _hardware_url:
                return Response({'code': 200, 'message': '请上传文件'}, status=status.HTTP_200_OK)
            _hardware_version = HardwareVersionModel()
            _hardware_version.category = _category
            _hardware_version.manufacture = _manufacture
            _hardware_version.hw_version = _hw_version
            _hardware_version.fw_version = _fw_version
            _hardware_version.hardware_url = _hardware_url
            _hardware_version.save()
            return Response({'code': 200, 'message': '上传成功'}, status=status.HTTP_201_CREATED)


class GetHardwareVersionList(generics.ListAPIView):
    """
    版本列表查询
    """
    queryset = HardwareVersionModel.objects.filter(is_delete=False).order_by('-fw_version')
    serializer_class = HardwareVersionSerializer
    pagination_class = LuckyScportPagination


class DelHardwareVersion(generics.DestroyAPIView):
    """
    硬件版本删除
    """

    def delete(self, request, *args, **kwargs):
        _hardware_version = HardwareVersionModel.objects.get(pk=kwargs['PK'])
        _hardware_version.is_delete = True
        _hardware_version.save()
        return Response({'code': 200, 'message': '删除成功'}, status=status.HTTP_200_OK)


class GetApkVersionList(generics.ListAPIView):
    """
    版本列表查询
    """
    queryset = ApkVersionModel.objects.filter(is_delete=False).order_by('-version_no')
    serializer_class = ApkVersionSerializer
    pagination_class = LuckyScportPagination


class DelApkVersion(generics.DestroyAPIView):
    """
    版本删除
    """

    def delete(self, request, *args, **kwargs):

        _apk_version = ApkVersionModel.objects.get(pk=kwargs['PK'])
        _version_no = ApkVersionModel.objects.filter(is_delete=False).aggregate(Max('version_no')).get(
            'version_no__max', None)

        _apk_version.is_delete = True
        _apk_version.save()
        # 如果删除的是最高版本包,则向下还原一个版本
        if _version_no == _apk_version.version_no:
            _recover_version_no = ApkVersionModel.objects.filter(is_delete=False).aggregate(Max('version_no')).get(
                'version_no__max', None)
            if _recover_version_no:
                recoverAPK(_recover_version_no)
        return Response({'code': 200, 'message': '删除成功'}, status=status.HTTP_200_OK)


class BatchAddUser(generics.CreateAPIView):
    """
    批量增加用户
    """

    def post(self, request, *args, **kwargs):
        # pass

        ACCTOUNT_FREFIX = "155444444"
        COUNT = 0
        NAME_PREFFIX_LIST = ['快乐的', '冷静的', '醉熏的', '潇洒的', '糊涂的', '积极的', '冷酷的', '深情的', '粗暴的', '温柔的', '可爱的', '愉快的', '义气的',
                             '认真的', '威武的', '帅气的', '传统的', '潇洒的', '漂亮的', '自然的', '专一的', '听话的', '昏睡的', '狂野的', '等待的', '搞怪的',
                             '幽默的', '魁梧的', '活泼的', '开心的', '高兴的', '超帅的', '留胡子的', '坦率的', '直率的', '轻松的', '痴情的', '完美的', '精明的',
                             '无聊的', '有魅力的', '丰富的', '繁荣的', '饱满的', '炙热的', '暴躁的', '碧蓝的', '俊逸的', '英勇的', '健忘的', '故意的', '无心的',
                             '土豪的', '朴实的', '兴奋的', '幸福的', '淡定的', '不安的', '阔达的', '孤独的', '独特的', '疯狂的', '时尚的', '落后的', '风趣的',
                             '忧伤的', '大胆的', '爱笑的', '矮小的', '健康的', '合适的', '玩命的', '沉默的', '斯文的', '香蕉', '苹果', '鲤鱼', '鳗鱼',
                             '任性的', '细心的', '粗心的', '大意的', '甜甜的', '酷酷的', '健壮的', '英俊的', '霸气的', '阳光的', '默默的', '大力的', '孝顺的',
                             '忧虑的', '着急的', '紧张的', '善良的', '凶狠的', '害怕的', '重要的', '危机的', '欢喜的', '欣慰的', '满意的', '跳跃的', '诚心的',
                             '称心的', '如意的', '怡然的', '娇气的', '无奈的', '无语的', '激动的', '愤怒的', '美好的', '感动的', '激情的', '激昂的', '震动的',
                             '虚拟的', '超级的', '寒冷的', '精明的', '明理的', '犹豫的', '忧郁的', '寂寞的', '奋斗的', '勤奋的', '现代的', '过时的', '稳重的',
                             '热情的', '含蓄的', '开放的', '无辜的', '多情的', '纯真的', '拉长的', '热心的', '从容的', '体贴的', '风中的', '曾经的', '追寻的',
                             '儒雅的', '优雅的', '开朗的', '外向的', '内向的', '清爽的', '文艺的', '长情的', '平常的', '单身的', '伶俐的', '高大的', '懦弱的',
                             '柔弱的', '爱笑的', '乐观的', '耍酷的', '酷炫的', '神勇的', '年轻的', '唠叨的', '瘦瘦的', '无情的', '包容的', '顺心的', '畅快的',
                             '舒适的', '靓丽的', '负责的', '背后的', '简单的', '谦让的', '彩色的', '缥缈的', '欢呼的', '生动的', '复杂的', '慈祥的', '仁爱的',
                             '魔幻的', '虚幻的', '淡然的', '受伤的', '雪白的', '高高的', '糟糕的', '顺利的', '闪闪的', '羞涩的', '缓慢的', '迅速的', '优秀的',
                             '聪明的', '含糊的', '俏皮的', '淡淡的', '坚强的', '平淡的', '欣喜的', '能干的', '灵巧的', '友好的', '机智的', '机灵的', '正直的',
                             '谨慎的', '俭朴的', '殷勤的', '虚心的', '辛勤的', '自觉的', '无私的', '无限的', '踏实的', '老实的', '现实的', '可靠的', '务实的',
                             '拼搏的', '个性的', '粗犷的', '活力的', '成就的', '勤劳的', '单纯的', '落寞的', '朴素的', '悲凉的', '忧心的', '洁净的', '清秀的',
                             '自由的', '小巧的', '单薄的', '贪玩的', '刻苦的', '干净的', '壮观的', '和谐的', '文静的', '调皮的', '害羞的', '安详的', '自信的',
                             '端庄的', '坚定的', '美满的', '舒心的', '温暖的', '专注的', '勤恳的', '美丽的', '腼腆的', '优美的', '甜美的', '甜蜜的', '整齐的',
                             '动人的', '典雅的', '尊敬的', '舒服的', '妩媚的', '秀丽的', '喜悦的', '甜美的', '彪壮的', '强健的', '大方的', '俊秀的', '聪慧的',
                             '迷人的', '陶醉的', '悦耳的', '动听的', '明亮的', '结实的', '魁梧的', '标致的', '清脆的', '敏感的', '光亮的', '大气的', '老迟到的',
                             '知性的', '冷傲的', '呆萌的', '野性的', '隐形的', '笑点低的', '微笑的', '笨笨的', '难过的', '沉静的', '火星上的', '失眠的',
                             '安静的', '纯情的', '要减肥的', '迷路的', '烂漫的', '哭泣的', '贤惠的', '苗条的', '温婉的', '发嗲的', '会撒娇的', '贪玩的',
                             '执着的', '眯眯眼的', '花痴的', '想人陪的', '眼睛大的', '高贵的', '傲娇的', '心灵美的', '爱撒娇的', '细腻的', '天真的', '怕黑的',
                             '感性的', '飘逸的', '怕孤独的', '忐忑的', '高挑的', '傻傻的', '冷艳的', '爱听歌的', '还单身的', '怕孤单的', '懵懂的']
        NAME_SUFFIX_LIST = ['嚓茶', '凉面', '便当', '毛豆', '花生', '可乐', '灯泡', '哈密瓜', '野狼', '背包', '眼神', '缘分', '雪碧', '人生', '牛排',
                            '蚂蚁', '飞鸟', '灰狼', '斑马', '汉堡', '悟空', '巨人', '绿茶', '自行车', '保温杯', '大碗', '墨镜', '魔镜', '煎饼', '月饼',
                            '月亮', '星星', '芝麻', '啤酒', '玫瑰', '大叔', '小伙', '哈密瓜，数据线', '太阳', '树叶', '芹菜', '黄蜂', '蜜粉', '蜜蜂',
                            '信封', '西装', '外套', '裙子', '大象', '猫咪', '母鸡', '路灯', '蓝天', '白云', '星月', '彩虹', '微笑', '摩托', '板栗',
                            '高山', '大地', '大树', '电灯胆', '砖头', '楼房', '水池', '鸡翅', '蜻蜓', '红牛', '咖啡', '机器猫', '枕头', '大船', '诺言',
                            '钢笔', '刺猬', '天空', '飞机', '大炮', '冬天', '洋葱', '春天', '夏天', '秋天', '冬日', '航空', '毛衣', '豌豆', '黑米',
                            '玉米', '眼睛', '老鼠', '白羊', '帅哥', '美女', '季节', '鲜花', '服饰', '裙子', '白开水', '秀发', '大山', '火车', '汽车',
                            '歌曲', '舞蹈', '老师', '导师', '方盒', '大米', '麦片', '水杯', '水壶', '手套', '鞋子', '自行车', '鼠标', '手机', '电脑',
                            '书本', '奇迹', '身影', '香烟', '夕阳', '台灯', '宝贝', '未来', '皮带', '钥匙', '心锁', '故事', '花瓣', '滑板', '画笔',
                            '画板', '学姐', '店员', '电源', '饼干', '宝马', '过客', '大白', '时光', '石头', '钻石', '河马', '犀牛', '西牛', '绿草',
                            '抽屉', '柜子', '往事', '寒风', '路人', '橘子', '耳机', '鸵鸟', '朋友', '苗条', '铅笔', '钢笔', '硬币', '热狗', '大侠',
                            '御姐', '萝莉', '毛巾', '期待', '盼望', '白昼', '黑夜', '大门', '黑裤', '钢铁侠', '哑铃', '板凳', '枫叶', '荷花', '乌龟',
                            '仙人掌', '衬衫', '大神', '草丛', '早晨', '心情', '茉莉', '流沙', '蜗牛', '战斗机', '冥王星', '猎豹', '棒球', '篮球', '乐曲',
                            '电话', '网络', '世界', '中心', '鱼', '鸡', '狗', '老虎', '鸭子', '雨', '羽毛', '翅膀', '外套', '火', '丝袜', '书包',
                            '钢笔', '冷风', '八宝粥', '烤鸡', '大雁', '音响', '招牌', '胡萝卜', '冰棍', '帽子', '菠萝', '蛋挞', '香水', '泥猴桃', '吐司',
                            '溪流', '黄豆', '樱桃', '小鸽子', '小蝴蝶', '爆米花', '花卷', '小鸭子', '小海豚', '日记本', '小熊猫', '小懒猪', '小懒虫', '荔枝',
                            '镜子', '曲奇', '金针菇', '小松鼠', '小虾米', '酒窝', '紫菜', '金鱼', '柚子', '果汁', '百褶裙', '项链', '帆布鞋', '火龙果',
                            '奇异果', '煎蛋', '唇彩', '小土豆', '高跟鞋', '戒指', '雪糕', '睫毛', '铃铛', '手链', '香氛', '红酒', '月光', '酸奶',
                            '银耳汤', '咖啡豆', '小蜜蜂', '小蚂蚁', '蜡烛', '棉花糖', '向日葵', '水蜜桃', '小蝴蝶', '小刺猬', '小丸子', '指甲油', '康乃馨',
                            '糖豆', '薯片', '口红', '超短裙', '乌冬面', '冰淇淋', '棒棒糖', '长颈鹿', '豆芽', '发箍', '发卡', '发夹', '发带', '铃铛',
                            '小馒头', '小笼包', '小甜瓜', '冬瓜', '香菇', '小兔子', '含羞草', '短靴', '睫毛膏', '小蘑菇', '跳跳糖', '小白菜', '草莓', '柠檬',
                            '月饼', '百合', '纸鹤', '小天鹅', '云朵', '芒果', '面包', '海燕', '小猫咪', '龙猫', '唇膏', '鞋垫', '羊', '黑猫', '白猫',
                            '万宝路', '金毛', '山水', '音响']

        for i in range(60):
            _app_user = AppUser()
            ACCOUNT_SUFFIX = '%02d' % COUNT

            _app_user.user_account = ACCTOUNT_FREFIX + ACCOUNT_SUFFIX
            COUNT = COUNT + 1
            _app_user.password = 123456
            _app_user.save()

            _user_info = UserInfo()
            # 头像
            _user_info.user = _app_user
            _user_info.portrait = "http://oq0zkmcec.bkt.clouddn.com/6a6569c006fc11e8b9c900163e1ad88a.png"
            _user_info.weight = random.randint(40, 80)
            _user_info.height = random.randint(155, 180)
            _user_info.nick_name = random.choice(NAME_PREFFIX_LIST) + random.choice(NAME_SUFFIX_LIST)
            _user_info.sex = random.choice([0, 1])
            _user_info.city = "宁波"
            _user_info.age = random.randint(16, 30)
            _user_info.birth_year = (2018 - _user_info.age)
            _user_info.birth_month = random.randint(1, 12)
            _user_info.continuity_sign = random.randint(1, 20)
            _user_info.target_weight = random.randint(40, 80)
            _user_info.save()


class UserBodyDemendionList(PageListView):
    """
    查询用户身体维度信息
    """
    serializer_class = AdminUserBodyDimensionSerializer
    queryset = UserBodyDimension.objects.filter(is_delete=False)

    def get_queryset(self):
        queryset = self.queryset.filter(user_id=self.kwargs['user_id'])
        return queryset


class UpdateUserBodyDemendion(generics.UpdateAPIView):
    serializer_class = UserBodyDimensionSerializer
    queryset = UserBodyDimension.objects.filter(is_delete=False)
    def patch(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)


        return SuccessHR("保存成功")


class PostUserBodyDimension(generics.CreateAPIView):
    """
    保存用户用户身体维度信息 UserBodyDimension
    """
    serializer_class = UserBodyDimensionSerializer

    def post(self, request, *args, **kwargs):
        _data = request.data.copy()
        # _data['user'] = request.app_user.userinfo.id
        serializer = UserBodyDimensionSerializer(data=_data)
        if serializer.is_valid():
            serializer.save()
            return SuccessHR("保存成功")
            # return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return ErrorHR(serializer.errors + "保存失败")
            # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class DelUserBodyDemendion(generics.DestroyAPIView):

    def delete(self, request, *args, **kwargs):
        UserBodyDimension.objects.filter(pk=kwargs['pk']).update(is_delete=True)
        return SuccessHR("删除成功")
